package com.chushouya.order.service.api.impl;

import com.chushouya.common.support.Contexts;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Strings;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.constants.UserOrderActionEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.admin.order.OrderQuery;
import com.chushouya.order.dto.api.order.OrderCancelApiDTO;
import com.chushouya.order.rabbitmq.sender.ExpressReservationMessageSender;
import com.chushouya.order.service.api.UserOrderActionCtrlService;
import com.chushouya.order.service.api.UserOrderActionService;
import com.chushouya.order.service.common.CommonOrderActionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
@Slf4j
public class UserOrderActionServiceImpl implements UserOrderActionService {

    @Resource
    private UserOrderActionCtrlService userOrderActionCtrlService;

    @Resource
    private CommonOrderActionService commonOrderActionService;

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private ExpressReservationMessageSender expressReservationMessageSender;


    private OrderEntity getOrder(String orderNo,Long userId) {
        OrderQuery query = new OrderQuery();
        query.setOrderNo(orderNo);
        query.setUserId(userId);
        OrderEntity orderEntity = orderRepository.selectOne(query);
        if (Objects.isNull(orderEntity)) {
            throw Ex.business("订单不存在");
        }
        return orderEntity;
    }


    @Override
    public void cancelOrder(OrderCancelApiDTO dto) {
        final Long userId = Contexts.getUserContext().getUserId();
        OrderEntity orderEntity = getOrder(dto.getOrderNo(),userId);
        userOrderActionCtrlService.actionExecuteCheck(UserOrderActionEnum.CANCEL,orderEntity);
        final String msg = Strings.format("用户取消订单,订单号:{} {}", orderEntity.getOrderNo(),Strings.defaultString(dto.getRemark()));
        commonOrderActionService.closeOrder(orderEntity,msg,OrderStatusEnum.CANCELLED.value());
        expressReservationMessageSender.sendExpressCancelMessage(orderEntity);
    }
}
